package com.nosweattechnet.server;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.nosweattechnet.datatypes.Item;

//Runs a query on the server which searches for items by keyword
public class ItemSearchAsyncTask extends CommunicatorAsyncTask {
	//Constants specified in php scripts
	private BasicNameValuePair tag=new BasicNameValuePair("tag","searchItems");
	private String itemNameString="item_name";
	private String placeIDString="place_uuid";
	
	//Initializes the Communicator, then adds the required tag, and then adds the keyword using the stored constant.
	public ItemSearchAsyncTask(String itemName) {
		super();
		super.addNameValuePair(tag);
		super.addNameValuePair(new BasicNameValuePair(itemNameString,itemName));
	}
	
	//Initializes the Communicator, adds the required tag, adds the keyword using the stored constant, and finally adds the placeid using the stored constant.
	public ItemSearchAsyncTask(String itemName,String placeid) {
		super();
		super.addNameValuePair(tag);
		super.addNameValuePair(new BasicNameValuePair(itemNameString,itemName));
		super.addNameValuePair(new BasicNameValuePair(placeIDString,placeid));
	}
	
	//Parses the resulting JSONArray to an ArrayList of Items
	//IF NO JSONARRAY IS RETURNED, I.E. NO ITEMS MATCHED THE KEYWORD, AN EMPTY LIST IS RETURNED.
	public ArrayList<Item> getItems() throws InterruptedException, ExecutionException{
		ArrayList<Item> ai=new ArrayList<Item>();
		JSONArray jarr=this.get();
		if(jarr==null){
			return ai;
		}
		for(int i=0;i<jarr.length();i++){
			try {
				ai.add(new Item(jarr.getJSONObject(i)));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return ai;
	}
}
